package mhe.mgt.detail;

import java.util.Date;

import mhe.mgt.Application;
import mhe.mgt.NavigationView;
import mhe.mgt.model.MchMachine;
import mhe.mgt.model.MchMachinePart;
import mhe.mgt.model.MchSystem;
import mhe.mgt.util.DateUtils;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.ui.ISharedImages;

public class DetailForm extends Composite implements Listener {
	private Text nameText;
	private Text noteText;
	private Date createDate;
	private Label createDateLabel;
	private ToolItem deleteItem;
	private ToolItem saveItem;
	private Label nameLabel;
	private Composite form;
	private Object parentItem;
	private Label parentLabel;
	private Label parentNameLabel;
	private Label lifeDayLabel;
	private Text lifeDayText;
	private Composite lifeDayComposite;
	public static DetailForm instance;

	public DetailForm(Composite parent, int style) {
		super(parent, style);
		instance = this;
		initBody();
	}

	private void initBody() {
		GridLayout layout = new GridLayout();
		layout.marginHeight = 0;
		layout.marginWidth = 0;
		this.setLayout(layout);
		GridData gd = new GridData(GridData.FILL_HORIZONTAL);
		ToolBar toolBar = new ToolBar(this, SWT.BORDER);
		layout = new GridLayout(5, true);
		layout.marginWidth = 10;
		toolBar.setLayout(layout);
		toolBar.setLayoutData(gd);
		saveItem = new ToolItem(toolBar, SWT.PUSH);
		saveItem.setImage(Application
				.getImage(ISharedImages.IMG_ETOOL_SAVE_EDIT));
		saveItem.setToolTipText(Messages.DetailForm_0);

		saveItem.addListener(SWT.Selection, new Listener() {

			@Override
			public void handleEvent(Event event) {
				saveInfor();
			}
		});

		deleteItem = new ToolItem(toolBar, SWT.PUSH);
		deleteItem.setImage(Application
				.getImage(ISharedImages.IMG_ETOOL_DELETE));
		deleteItem.setToolTipText(Messages.DetailForm_1);
		deleteItem.setEnabled(false);

		deleteItem.addListener(SWT.Selection, new Listener() {

			@Override
			public void handleEvent(Event event) {
				deleteItem();
			}
		});

		// top banner
		form = new Composite(this, SWT.NONE);
		form.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_FILL,
				GridData.VERTICAL_ALIGN_BEGINNING, true, false));
		layout = new GridLayout();
		layout.marginHeight = 5;
		layout.marginWidth = 10;
		layout.numColumns = 2;
		form.setLayout(layout);

		// setup bold font
		Font boldFont = JFaceResources.getFontRegistry().getBold(
				JFaceResources.DEFAULT_FONT);

		nameLabel = new Label(form, SWT.WRAP);
		nameLabel.setText(Messages.DetailForm_2);
		nameLabel.setFont(boldFont);
		nameText = new Text(form, SWT.BORDER);
		GridData ld = new GridData();
		ld.widthHint = 200;
		nameText.setLayoutData(ld);

		createDate = new Date();
		Label l = new Label(form, SWT.WRAP);
		l.setText(Messages.DetailForm_3);
		l.setFont(boldFont);
		createDateLabel = new Label(form, SWT.WRAP);
		createDateLabel.setText(DateUtils.formatDateTime(createDate));

		ld = new GridData();
		ld.heightHint = 0;
		parentLabel = new Label(form, SWT.WRAP);
		parentLabel.setText(Messages.DetailForm_4);
		parentLabel.setFont(boldFont);
		parentLabel.setLayoutData(ld);
		parentNameLabel = new Label(form, SWT.WRAP);
		parentNameLabel.setFont(boldFont);
		parentNameLabel.setForeground(getDisplay().getSystemColor(SWT.COLOR_BLUE));
		parentNameLabel.setText(Messages.DetailForm_5);
		parentNameLabel.setLayoutData(ld);
		
		lifeDayLabel = new Label(form, SWT.WRAP);
		lifeDayLabel.setText(Messages.DetailForm_6);
		lifeDayLabel.setFont(boldFont);
		lifeDayLabel.setLayoutData(ld);
		lifeDayComposite = new Composite(form, SWT.NONE);
		lifeDayComposite.setLayout(new FillLayout());
		gd = new GridData();
		gd.widthHint = 200;
		gd.heightHint = 0;
		lifeDayComposite.setLayoutData(gd);
		lifeDayText = new Text(lifeDayComposite, SWT.BORDER);

		l = new Label(form, SWT.WRAP);
		l.setText(Messages.DetailForm_7);
		l.setFont(boldFont);
		noteText = new Text(this, SWT.MULTI | SWT.WRAP | SWT.V_SCROLL);
		noteText.setLayoutData(new GridData(GridData.FILL_BOTH));

		NavigationView.addSelectionListener(this);
	}

	public void deleteItem() {
		Object obj = getData();
		if (obj != null) {
			if (obj instanceof MchSystem) {
				MchSystem sys = (MchSystem) obj;
				boolean re = MessageDialog.openConfirm(Application.mainShell,
						Messages.DetailForm_8, Messages.DetailForm_9
								+ sys.getName() + Messages.DetailForm_10);
				if (re) {
					Application.systemService.delete(sys);

					NavigationView.instance().refresh();

					Application.setStatusLine(Application
							.getImage(ISharedImages.IMG_ETOOL_DELETE),
							Messages.DetailForm_11 + sys.getName()
									+ Messages.DetailForm_12);

					resetForm();
				}
			} else if (obj instanceof MchMachine) {
				MchMachine m = (MchMachine) obj;
				boolean re = MessageDialog.openConfirm(Application.mainShell,
						Messages.DetailForm_13, Messages.DetailForm_14
								+ m.getName()
								+ Messages.DetailForm_15
								+ Application.systemService.find(
										m.getSystemId()).getName() + Messages.DetailForm_16);
				if (re) {
					Application.machineService.delete(m);

					NavigationView.instance().refresh();

					Application.setStatusLine(Application
							.getImage(ISharedImages.IMG_ETOOL_DELETE),
							Messages.DetailForm_17
									+ m.getName()
									+ Messages.DetailForm_18
									+ Application.systemService.find(
											m.getSystemId()).getName() + Messages.DetailForm_19);

					resetForm();
				}
			} else if (obj instanceof MchMachinePart) {
				MchMachinePart m = (MchMachinePart) obj;
				boolean re = MessageDialog.openConfirm(Application.mainShell,
						Messages.DetailForm_20, Messages.DetailForm_21
								+ m.getName()
								+ Messages.DetailForm_22
								+ Application.machineService.find(
										m.getMachineId()).getName() + Messages.DetailForm_23);
				if (re) {
					Application.machinePartService.delete(m);

					DetailTable.instance.refreshTable();

					Application.setStatusLine(Application
							.getImage(ISharedImages.IMG_ETOOL_DELETE),
							Messages.DetailForm_24
									+ m.getName()
									+ Messages.DetailForm_25
									+ Application.machineService.find(
											m.getMachineId()).getName() + Messages.DetailForm_26);

					resetForm();
				}
			}
		}
	}

	private void enableDeleteItem(boolean b) {
		deleteItem.setEnabled(b);
	}

	private void resetForm() {
		nameText.setText(Messages.DetailForm_27);
		createDate = new Date();
		createDateLabel.setText(DateUtils.formatDateTime(createDate));
		noteText.setText(Messages.DetailForm_28);
		parentNameLabel.setText(Messages.DetailForm_29);
		lifeDayText.setText(Messages.DetailForm_30);
		enableDeleteItem(false);
		setData(null);
	}

	public void saveInfor() {
		if (getItemName().isEmpty()) {
			Application.openInformation(Messages.DetailForm_31, Messages.DetailForm_32);
			return;
		}
		/*Calendar ca = Calendar.getInstance();
		ca.add(Calendar.DAY_OF_MONTH, -3);
		createDate = ca.getTime();*/
		if (parentItem == null) { // add new system
			MchSystem sys = new MchSystem();
			if (getData() != null) {
				sys = (MchSystem) getData();
			}
			sys.setName(getItemName());
			sys.setCreateDate(createDate);
			sys.setUpdateDate(createDate);
			sys.setCreateUser(Application.USER);
			sys.setNote(getNote());
			if (getData() != null) {
				sys.setUpdateDate(new Date());
				Application.systemService.update(sys);
				Application.setStatusLineInfor(Messages.DetailForm_33 + sys.getName() + Messages.DetailForm_34);
			} else {
				Application.systemService.add(sys);
				setData(sys);
				Application.setStatusLineInfor(Messages.DetailForm_35 + sys.getName()
								+ Messages.DetailForm_36);
				enableDeleteItem(true);
			}
			NavigationView.instance().refresh();
		} else if (parentItem instanceof MchSystem) { // add new machine
			MchMachine machine = new MchMachine();
			if (getData() != null) {
				machine = (MchMachine) getData();
			}
			MchSystem p = (MchSystem) parentItem;
			machine.setName(getItemName());
			machine.setCreateDate(createDate);
			machine.setUpdateDate(createDate);
			machine.setCreateUser(Application.USER);
			machine.setNote(getNote());
			machine.setSystemId(p.getId());
			if (getData() != null) {
				machine.setUpdateDate(new Date());
				Application.machineService.update(machine);
				Application.setStatusLine(Application
						.getImage(ISharedImages.IMG_OBJS_INFO_TSK),
						Messages.DetailForm_37 + machine.getName()
								+ Messages.DetailForm_38 + p.getName() + Messages.DetailForm_39);
			} else {
				Application.machineService.add(machine);
				setData(machine);
				Application.setStatusLine(Application
						.getImage(ISharedImages.IMG_OBJS_INFO_TSK),
						Messages.DetailForm_40 + machine.getName()
								+ Messages.DetailForm_41 + p.getName() + Messages.DetailForm_42);
				enableDeleteItem(true);
			}
			NavigationView.instance().refresh();
		} else if (parentItem instanceof MchMachine) { // add new machine part
			if (lifeDayText.getText().trim().isEmpty()) {
				Application.openInformation(Messages.DetailForm_43,
						Messages.DetailForm_44);
				return;
			}
			int maxLifeDay = 0;
			try {
				maxLifeDay = Integer.parseInt(lifeDayText.getText().trim());
			} catch (Exception e) {
				Application.setStatusLineError(Messages.DetailForm_45);
				lifeDayText.forceFocus();
				lifeDayText.selectAll();
				return;
			}
			MchMachinePart mp = new MchMachinePart();
			if (getData() != null) {
				mp = (MchMachinePart) getData();
				// reset create date if change the max life day
				if (mp.getMaxLifeDay() != maxLifeDay) {
					createDate = new Date();
				}
			}
			MchMachine p = (MchMachine) parentItem;
			mp.setName(getItemName());
			mp.setCreateDate(createDate);
			mp.setUpdateDate(createDate);
			mp.setCreateUser(Application.USER);
			mp.setNote(getNote());
			mp.setMachineId(p.getId());
			mp.setMaxLifeDay(maxLifeDay );
			if (getData() != null) {
				mp.setUpdateDate(new Date());
				Application.machinePartService.update(mp);
				Application.setStatusLineInfor(Messages.DetailForm_46 + mp.getName()
								+ Messages.DetailForm_47 + p.getName() + Messages.DetailForm_48);
			} else {
				Application.machinePartService.add(mp);
				setData(mp);
				Application.setStatusLineInfor(Messages.DetailForm_49 + mp.getName()
								+ Messages.DetailForm_50 + p.getName() + Messages.DetailForm_51);
				enableDeleteItem(true);
			}
			DetailTable.instance.refreshTable();
		}
	}
	
	private String getNote() {
		String s = noteText.getText().trim();
		if (s.length() > 5000) {
			s = s.substring(0, 50);
		}
		return s;
	}

	private String getItemName() {
		String s = nameText.getText().trim();
		if (s.length() > 50) {
			s = s.substring(0, 50);
		}
		return s;
	}

	@Override
	public void handleEvent(Event event) {
		Object obj = event.data;
		parentItem = null;
		setData(obj);
		if (obj != null) {
			if (obj instanceof MchSystem) {
				MchSystem sys = (MchSystem) obj;
				nameLabel.setText(Messages.DetailForm_52);
				form.layout();
				nameText.setText(sys.getName());
				createDate = sys.getCreateDate();
				createDateLabel.setText(DateUtils.formatDateTime(createDate));
				noteText.setText(sys.getNote());
			} else if (obj instanceof MchMachine) {
				MchMachine m = (MchMachine) obj;
				nameLabel.setText(Messages.DetailForm_53);
				nameText.setText(m.getName());
				parentLabel.setText(Messages.DetailForm_54);
				parentItem = Application.systemService.find(
						m.getSystemId());
				parentNameLabel.setText(((MchSystem)parentItem).getName());
				createDate = m.getCreateDate();
				createDateLabel.setText(DateUtils.formatDateTime(createDate));
				noteText.setText(m.getNote());
			} else if (obj instanceof MchMachinePart) {
				MchMachinePart mp = (MchMachinePart) obj;
				nameLabel.setText(Messages.DetailForm_55);
				nameText.setText(mp.getName());
				parentLabel.setText(Messages.DetailForm_56);
				MchMachine m = Application.machineService.find(mp.getMachineId());
				parentItem = m;
				MchSystem sys = Application.systemService.find(m.getSystemId());
				parentNameLabel.setText(m.getName() + Messages.DetailForm_57 + sys.getName() + Messages.DetailForm_58);
				createDate = mp.getCreateDate();
				createDateLabel.setText(DateUtils.formatDateTime(createDate));
				noteText.setText(mp.getNote());
				lifeDayText.setText(String.valueOf(mp.getMaxLifeDay()));
			}
			enableDeleteItem(true);
			refreshFormLayout(obj.getClass());
		}
	}

	private void refreshFormLayout(Class<?> obj) {
		int height = 0;
		int lifeHeight = 0;
		if (obj == null || obj == MchSystem.class) {
			
		} else if (obj == MchMachine.class) {
			height = SWT.DEFAULT;
		} else if (obj == MchMachinePart.class) {
			height = SWT.DEFAULT;
			lifeHeight = SWT.DEFAULT;
		}
		GridData ld = new GridData();
		ld.heightHint = height;
		parentLabel.setLayoutData(ld);
		ld = new GridData();
		ld.heightHint = height;
		parentNameLabel.setLayoutData(ld);
		ld = new GridData();
		ld.heightHint = lifeHeight;
		lifeDayLabel.setLayoutData(ld);
		ld = (GridData) lifeDayComposite.getLayoutData();
		ld.heightHint = lifeHeight;
		lifeDayComposite.setLayoutData(ld);
		
		layout();
	}

	public void addSystemForm() {
		parentItem = null;
		nameLabel.setText(Messages.DetailForm_59);
		resetForm();
		refreshFormLayout(MchSystem.class);
		Application.setStatusLine(Application
				.getImage(ISharedImages.IMG_OBJ_ADD), Messages.DetailForm_60);
	}

	public void addMachineForm() {
		parentItem = getData();
		if (parentItem == null || !(parentItem instanceof MchSystem)) {
			Application.openInformation(Messages.DetailForm_61,
					Messages.DetailForm_62);
			return;
		}
		// set data for adding
		resetForm();
		nameLabel.setText(Messages.DetailForm_63);
		parentNameLabel.setText(((MchSystem) parentItem).getName());
		refreshFormLayout(MchMachine.class);
		Application.setStatusLine(Application
				.getImage(ISharedImages.IMG_OBJ_ADD), Messages.DetailForm_64);
	}

	public void addMachinePartForm() {
		if (getData() instanceof MchMachine) {
			parentItem = getData();
		}
		if (parentItem == null || !(parentItem instanceof MchMachine)) {
			Application.openInformation(Messages.DetailForm_65,
					Messages.DetailForm_66);
			return;
		}
		// set data for adding
		resetForm();
		nameLabel.setText(Messages.DetailForm_67);
		parentLabel.setText(Messages.DetailForm_68);
		parentNameLabel.setText(((MchMachine) parentItem).getName());
		refreshFormLayout(MchMachinePart.class);
		Application.setStatusLine(Application
				.getImage(ISharedImages.IMG_OBJ_ADD), Messages.DetailForm_69);
	}
}
